<?php

namespace app\common\model\mall\goods;

use think\Model;
use fast\Tree;

class Cat extends Model
{
    // 表名
    protected $name = 'mall_goods_cat';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'status_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
        });
    }

    
    public function getStatusList()
    {
        return ['normal' => __('Normal'),'hidden' => __('Hidden')];
    }     


    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public static function getTreeList($selected = [])
    {
    	$catList = collection(self::where('status', 'normal')->order('pid,weigh,id')->select())->toArray();
        $nodeList = [];
        Tree::instance()->init($catList);
        $catList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'simplename');
        $hasChildrens = [];
        foreach ($catList as $v)
        {
            if ($v['haschild'])
                $hasChildrens[] = $v['id'];
        }
        foreach ($catList as $v) {
            $state = array('selected' => in_array($v['id'], $selected) && !in_array($v['id'], $hasChildrens));
            $nodeList[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => __($v['simplename']), 'state' => $state);
        }
        return $nodeList;
    }
    
    /**
     * 获取列表
     */
    public function listQuery($parentId,$isFloor = -1){
        $dbo = $this->where(['status'=>'normal','showis'=>1,'pid'=>$parentId]);
        if($isFloor!=-1)$dbo->where('flooris',$isFloor);
        return $dbo->order('weigh asc')->column("id,name,pid,weigh,showis,flooris,commissionrate,simplename","id");
    }
    
    /**
     * 根据父分类获取其下所有子分类ID[包括自己]
     */
    public function getChildIds($ids,$data = []){
        if($ids!=0)$data = array_merge($data,$ids);
        $rs = $this->where(['status'=>'normal','showis'=>1,'pid'=>['in',$ids]])->column('id');
        if(count($rs)>0){
            return $this->getChildIds($rs,$data);
        }else{
            return $data;
        }
    }
    
    /**
     * 根据子分类获取其父级分类ID
     */
    public function getParentIds($id,$data = array()){
        $data[] = $id;
        $pid = $this->where('id',$id)->value('pid');
        if($pid==0){
            krsort($data);
            return $data;
        }else{
            return $this->getParentIds($pid, $data);
        }
    }
    /**
     * 根据子分类获取其父级分类名称
     */
    public function getParentNames($id){
        if($id<=0)return [];
        $ids = $this->getParentIds($id);
        $rs = $this->where('id','in',$ids)->field('name')->select();
        $names = [];
        foreach($rs as $v){
            $names[] = $v['name'];
        }
        return $names;
    }

    /**
     * 获取首页楼层
     */
    public function getFloors(){
        $cats1 = $this->where(['status'=>'normal','showis'=>1,'pid'=>0,'flooris'=>1])
            ->field("name,id,subtitle")->order('weigh desc')->limit(10)->select();
        if(!empty($cats1)){
            $ids = [];
            foreach ($cats1 as $key =>$v){
                $ids[] = $v['id'];
            }
            $cats2 = [];
            $rs = $this->where(['status'=>'normal','showis'=>1,'pid'=>['in',$ids],'flooris'=>1])
                ->field("pid,name,id,subtitle")->order('weigh desc')->select();
            foreach ($rs as $key => $v){
                $cats2[$v['pid']][] = $v;
            }
            foreach ($cats1 as $key =>$v){
                $cats1[$key]['children'] = (isset($cats2[$v['id']]))?$cats2[$v['id']]:[];
            }
        }
        return $cats1;
    }
    
    /**
     * 获取首页左侧分类、推荐品牌和广告
     */
    public static function getSideCategorys(){
        $data = cache('MALL_SIDE_CATS');
        if(!$data){
            $cats1 = self::where(['status'=>'normal', 'showis' => 1,'pid'=>0])->field("name,id")->order('weigh desc')->select();
            if(count($cats1)>0){
                $ids1 = [];$ids2 = [];$cats2 = [];$cats3 = [];$mcats3 = [];$mcats2 = [];
                foreach ($cats1 as $key =>$v){
                    $ids1[] = $v['id'];
                }
                $tmp2 = self::where(['status'=>'normal', 'showis'=>1,'pid'=>['in',$ids1]])->field("name,id,pid")->order('weigh asc')->select();
                if(count($tmp2)>0){
                    foreach ($tmp2 as $key =>$v){
                        $ids2[] = $v['id'];
                    }
                    $tmp3 = self::where(['status'=>'normal','showis'=>1,'pid'=>['in',$ids2]])->field("name,id,pid")->order('weigh asc')->select();
                    if(count($tmp3)>0){
                        //组装第三级
                        foreach ($tmp3 as $key =>$v){
                            $mcats3[$v['pid']][] = $v;
                        }
                    }
                    //组装第二级
                    foreach ($tmp2 as $key =>$v){
                        if(isset($mcats3[$v['id']]))$v['list'] = $mcats3[$v['id']];
                        $mcats2[$v['pid']][] = $v;
                    }
                    //组装第一级
                    foreach ($cats1 as $key =>$v){
                        if(isset($mcats2[$v['id']]))$cats1[$key]['list'] = $mcats2[$v['id']];
                    }
                }
                unset($ids1,$ids2,$cats2,$cats3,$mcats3,$mcats2);
            }
            cache('MALL_SIDE_CATS',$cats1);
            return $cats1;
        }
        return $data;
    }

    /**
     * 获取分类的佣金
     */
    public static function getCommissionRate($goodsCatId){
        $cats = self::where('id',$goodsCatId)->field('pid,commissionrate')->find();
        if(empty($cats)){
            return 0;
        }else{
            if((float)$cats['commissionrate']>=0)
                return (float)$cats['commissionrate'];
            else
                return self::getCommissionRate($cats['pid']);
        }
    }


public function brands()
    {
        return $this->belongsToMany('\app\common\model\mall\goods\Brand','mall_goods_catbrand','brandId','id');
    }

}
